package com.fatmeraid.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.fatmeraid.common.exception.FarmException;
import com.fatmeraid.common.login.LoginUser;
import com.fatmeraid.common.login.LoginUserHolder;
import com.fatmeraid.common.result.ResultCodeEnum;
import com.fatmeraid.dao.UserDao;
import com.fatmeraid.domain.User;
import com.fatmeraid.service.UserCenterService;
import com.fatmeraid.vo.user.ModifyPasswordVo;
import com.fatmeraid.vo.user.ModifyUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

@Service
public class UserCenterServiceImpl implements UserCenterService {
	@Autowired
	private UserDao userDao;
	@Override
	public boolean updateUserInfo(ModifyUserVo modifyUserVo) {
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		LambdaUpdateWrapper<User> luw = new LambdaUpdateWrapper<>();
		luw.eq(User::getUserId, userId);

		luw.set(modifyUserVo.getRealName()!=null, User::getRealName, modifyUserVo.getRealName());
		luw.set(modifyUserVo.getPhone()!=null, User::getPhone, modifyUserVo.getPhone());
		luw.set(modifyUserVo.getEmail()!=null, User::getEmail, modifyUserVo.getEmail());
		luw.set(modifyUserVo.getAddress()!=null, User::getAddress, modifyUserVo.getAddress());
		luw.set(modifyUserVo.getAvatar()!=null, User::getAvatar, modifyUserVo.getAvatar());
		int update = userDao.update(luw);
		return update > 0;
	}

	@Override
	public boolean updatePassword(ModifyPasswordVo modifyPasswordVo) {
		LoginUser loginUser = LoginUserHolder.getLoginUser();
		Long userId = loginUser.getUserId();
		// 判断输入密码是否为空
		if (modifyPasswordVo.getOldPassword() == null || modifyPasswordVo.getOldPassword().isEmpty()
			|| modifyPasswordVo.getNewPassword() == null || modifyPasswordVo.getNewPassword().isEmpty()){
			throw new FarmException(ResultCodeEnum.ADMIN_PASSWORD_NOT_EMPTY);
		}

		// 验证旧密码
		User user = userDao.selectOneByUserId(userId);
		// 对旧密码进行 MD5 加密
		String oldPasswordEncrypted = DigestUtils.md5DigestAsHex(
				modifyPasswordVo.getOldPassword().getBytes(StandardCharsets.UTF_8)
		);

		// 验证旧密码是否正确
		if (!user.getPassword().equals(oldPasswordEncrypted)){
			throw new FarmException(ResultCodeEnum.ADMIN_OLD_PASSWORD_ERROR);
		}
		// 验证新密码是否一致
		if (modifyPasswordVo.getNewPassword().equals(modifyPasswordVo.getOldPassword())){
			throw new FarmException(ResultCodeEnum.ADMIN_NEW_PASSWORD_ERROR);
		}

		//对输入密码进行 MD5 加密
		String inputEncrypted = DigestUtils.md5DigestAsHex(
				modifyPasswordVo.getNewPassword().getBytes(StandardCharsets.UTF_8)
		);
		user.setPassword(inputEncrypted);
		int update = userDao.updateById(user);
		return update > 0;
	}
}
